package com.chenhy.server.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

// 自定义Authority属性的反序列化过程
// 因为jackson的反序列化方式是需要无参构造来构造一个对象然后用set往里面设置值的
// 而我们使用的Authority的实现类SimpleGrantedAuthority刚好就没有无参构造，所以我们需要自定义一个反序列化过程给SimpleGrantedAuthority使用
public class CustomAuthorityDeserializer extends JsonDeserializer {
    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        // 拿到om
        ObjectCodec om = jsonParser.getCodec();
        // 读取树
        JsonNode jsonNode = ((JsonNode) om.readTree(jsonParser));
        // 准备list
        List<GrantedAuthority> grantedAuthorities = new LinkedList();

        // 拿到元素迭代器
        Iterator<JsonNode> elements = jsonNode.elements();
        while (elements.hasNext()){
            JsonNode next = elements.next();
            // 拿到需要自定义反序列化的参数的JsonNode
            JsonNode authority = next.get("authority");
            // 拿到序列化时对象里面的值然后新建对象并将该对象加入到准备好的List
            grantedAuthorities.add(new SimpleGrantedAuthority(authority.asText()));
        }
        return grantedAuthorities;
    }
}
